var course_self_add = new Object();
course_self_add.businessIds = [];
course_self_add.deptIds=[];
course_self_add.init = function(){
    course_self_add.handle();
    if($("#intId").val() != ""){
        $("#varCode").removeAttr("oninput").removeAttr("onblur");
    };
    // 加载基本信息
    initBaseInfo($("#intId").val());
}

course_self_add.handle = function () {
    //返回
    $("#btn_back").click(function () {
        parent.layer.closeAll();
    });
};


function varCodeValue(obj) {
    var no = $(obj).val();
    if(no.length < 2){
        $(obj).val("ZZ");
        return;
    }
    if(no.substring(0,2) != "ZZ"){
        $(obj).val("ZZ"+no);
    }
}

// 课程编号是否存在
function ifNoExist() {
    $.ajax({
        url: appPath+"/admin/exCourseSelf/isNoExist/" + $("#varCode").val(),
        data: {},
        dataType: "json",
        async: false,
        type: "GET",
        success: function (json) {
            var res = eval(json).result;
            if (res == "error") {
                layer.msg(json.message);
                return false;
            }else{
                return true;
            }
        }
    });
}


//加载自制课程基本信息
function initBaseInfo(intId){
    if("" == intId){
        // 初始化课程已选择的共享范围
        course_self_add.initCompanyTree("");
    }else{
        $.ajax({
            url: appPath + '/admin/exCourseSelf/selectOne/' + intId,
            data: {},
            dataType: "json",
            async: true,
            type: "GET",
            success: function (data) {
                var result = eval(data).result;
                if (result == "success") {
                    var course = eval(data).data;
                    $("#varCoverInfo").val(course.varCoverInfo);
                    $("#chrType").val(course.chrType);
                    $("#intCompanyId").val(course.intCompanyId);
                    $("#chrSource").val(course.chrSource);
                    $("#chrPlatformType").val(course.chrPlatformType);
                    $("#chrStatus").val(course.chrStatus);
                    $("#varCreateUser").val(course.varCreateUser);
                    $("#varOperUser").val(course.varOperUser);
                    $("#varCode").val(course.varCode).attr("readonly",true);;
                    $("#varName").val(course.varName);
                    $("#intTypeId").val(course.intTypeId);
                    $("#courseTypeName").val(data.courseTypeName);
                    $("#intClassHour").val(course.intClassHour);
                    $("#varDesc").val(course.varDesc);
                    if(data.imgSrc != ""){
                        $("#showHeaderImg").attr("src", data.imgSrc).show();
                    }

                    //自主练习权限
                    if (course.practiceLimits == '3') {
                        $("#practiceLimit1").click();
                        $("#practiceLimit3").click();
                    }else if(course.practiceLimits == '4') {
                        $("#practiceLimit1").click();
                        $("#practiceLimit4").click();
                    }else if(course.practiceLimits == '2') {
                        $("#practiceLimit2").click();
                    } else {
                        $("#practiceLimit1").click();
                        $("#practiceLimit3").click();
                    }

                    // 初始化课程已选择的共享范围
                    course_self_add.initCompanyTree(course.sharedScope);

                }
            }
        })
    }

}


function courseFormSave(){

    if($("#varName").val() == ""){
        layer.msg("请输入课程名称！");
        return;
    }
    if($("#intTypeId").val() == ""){
        layer.msg("请选择课程类别！");
        return;
    }
    if($("#intClassHour").val() == ""){
        layer.msg("请输入课时（分）！");
        return;
    }
    if(course_self_add.deptIds.length > 0){
        $("#sharedScope").val(course_self_add.deptIds.join(","));
    }

    var form = $("#courseForm");
    var options  = {
        url: appPath + "/admin/exCourseSelf/saveExCourse",
        success: function (datas) {
            if(datas.result == "success"){
                layer.alert('保存成功', {icon: 1,  skin: 'layer-ext-moon'}, function(index){
                    history.go(-1);
                });
            }else{
                layer.alert('操作失敗', {icon: 2,  skin: 'layer-ext-moon'});
            }
        }
    };
    form.ajaxSubmit(options);
}




//初始化受训单位列表
course_self_add.initCompanyTree = function(sharedScope) {
    $("#company_tree_select2").select2();
    $.ajax({
        url: appPath+ '/admin/project_create/private/trainDepartment',
        dataType: 'json',
        type:'get',
        success:function (data) {
            var list = data.result;
            $("#company_tree_select2").select2({
                tags:true,
                data:list,
                multiple:true,
                placeholder:"请选择要共享的部门",
                language:"zh-CN"
            });

            if("" != sharedScope){
                var deptIds = sharedScope.split(",");
                course_self_add.deptIds = deptIds;
                $("#company_tree_select2").val(deptIds).trigger("change");
            }

            //点击小X触发，取消树中节点的勾选状态
            course_self_add.deleteDept();

        }

    })

}
course_self_add.selectDept = function(){
    //得到最新的受训单位数据
    var departments = $("#company_tree_select2").select2("data");
    course_self_add.getNewDate(departments);
    //$('.por').addClass('show');
    // 弹窗-选择部门
    layer.open({
        type: 2,
        title: '选择部门',
        shadeClose: false,				//true点击遮罩层关闭
        shade: 0.3,					//遮罩层背景
        maxmin: true, 					// 开启最大化最小化按钮
        area: ['  px', '60%'],		//弹出层大小
        scrollbar: false,				//false隐藏滑动块
        content: [appPath + '/popup/selectDept2Checkbox?companyId=' + $("#intCompanyId").val() + "&deptIds= " + course_self_add.deptIds.join(","), 'yes']
    });
};

//得到最新的受训单位数据
course_self_add.getNewDate=function(datas){
    var deptDatas = [];
    for(var i = 0;i<datas.length;i++){
        deptDatas.push(datas[i].id);
    }
    course_self_add.deptIds = deptDatas;
}

//隐藏树下拉框
course_self_add.close = function(event){
    $('.por').removeClass('show');
}
// 确定受训角色
course_self_add.finish = function(departmentIds){
    course_self_add.deptIds = departmentIds;
    $("#company_tree_select2").val(departmentIds).trigger("change");

};

//点击小X触发，取消树中节点的勾选状态
course_self_add.deleteDept = function () {
    $(document).delegate('.select2-selection__choice__remove','click',function(){
        var id = $(this).parent().attr('id');
        var treeObj = $.fn.zTree.getZTreeObj(tree_options.id);
        var node = treeObj.getNodeByParam("id", id, null);
        node.checked = false ;
        treeObj.updateNode(node);
    })
}

//弹窗选择部门后回调
course_self_add.getDept = function (depatements) {
    // 组装数据
    for(var i=0; i< depatements.length; i++) {
        if(step1.repeatDept(depatements[i],step1.deptIds)){
            course_self_add.deptIds.push(depatements[i])
        }
    }

}